package com.boarsoft.boar.batch.biz;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.boarsoft.boar.batch.entity.BatchLock;
import com.boarsoft.common.Util;
import com.boarsoft.hibernate.biz.SimpleBizImpl;

@Component
public class BatchLockBizImpl extends SimpleBizImpl implements BatchLockBiz {

	@Override
	@Transactional(readOnly = true)
	public BatchLock get(String code) {
		return dao.get(BatchLock.class, code);
	}

	@Override
	@Transactional
	public Object save(BatchLock o) {
		if (Util.strIsEmpty(o.getCode())) {
			return dao.save(o);
		} else {
			return dao.merge(o);
		}
	}

	@Override
	@Transactional
	public boolean optimisticLock(BatchLock batchLock, String addr) {
		StringBuilder sb = new StringBuilder();
		sb.append("update ").append(BatchLock.class.getName());
		sb.append(" set version = version + 1, addr = '").append(addr).append("'");
		sb.append(" where code = '").append(batchLock.getCode()).append("'");
		sb.append(" and version = ").append(batchLock.getVersion());
		int i = dao.createQuery(sb.toString()).executeUpdate();
		if (i == 1)
			return true;
		return false;
	}

	@Override
	@Transactional
	public boolean pessimisticLock(String code, String addr) {
		StringBuilder sb = new StringBuilder();
		sb.append("update ").append(BatchLock.class.getName());
		sb.append(" set version = version + 1, addr = '").append(addr).append("'");
		sb.append(" where code = '").append(code).append("'");
		int i = dao.createQuery(sb.toString()).executeUpdate();
		if (i == 1)
			return true;
		return false;
	}

	@Override
	@Transactional
	public boolean updateStatus(String code, short status) {
		StringBuilder sb = new StringBuilder();
		sb.append("update ").append(BatchLock.class.getName());
		sb.append(" set version = version + 1, status = '").append(status).append("'");
		sb.append(" where code = '").append(code).append("'");
		int i = dao.createQuery(sb.toString()).executeUpdate();
		if (i == 1)
			return true;
		return false;
	}
}
